<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.push('/layout/home')"
    />
    <van-search
      v-model.trim="key"
      shape="round"
      show-action
      placeholder="请输入搜索关键词"
      @input="oninput"
      @search="onSearch"
    >
      <template #action> <div @click="onSearch">搜索</div> </template>
    </van-search>

    <!-- 历史记录区域 -->
    <!-- v-if="!key" ！null即是不空->true -->
    <van-cell-group v-if="!key">
      <van-cell title="历史记录"
        ><span class="clearlog" @click="ClearRecord">清除记录</span></van-cell
      >
      <div v-if="clear">
        <van-cell
          :title="item"
          v-for="(item, index) in historyList"
          :key="index"
          @click="$router.push({ name: 'result', query: { key: item } })"
        />
      </div>
    </van-cell-group>

    <!-- 联想区域 -->
    <!-- :title="item"组件不能解析原生的v-html方法 -->

    <van-cell-group v-else>
      <!-- item是被<span>包装过的数据，利用原生数据suggestList，数据是一样的，也可以利用 -->
      <van-cell
        icon="search"
        v-for="(item, index) in colocSuggestList"
        :key="index"
        @click="
          $router.push({ name: 'result', query: { key: suggestList[index] } })
        "
      >
        <div v-html="item"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { suggestAPI, getHistoryAPI } from "@/api";
export default {
  name: "search",
  data() {
    return {
      key: "",
      suggestList: [], //搜索得到的数据数组

      timerId: "", //防抖计时器
      // historyList: [], //旧接口数据 暂不用到
      historyList: JSON.parse(window.localStorage.getItem("history")) || [], //存放历史记录

      clear: true, //清除历史记录
    };
  },
  methods: {
    //搜索按钮的点击事件
    onSearch() {
      // console.log(this.historyList);
      //跳转到结果页面()
      if (this.key) {
        //如果本次搜索结果不在里面就保存起来
        if (!this.historyList.includes(this.key)) {
          // 把key加到数组(最后一次搜索的放在第一个)
          this.historyList.unshift(this.key);
        }
        // 把数组保存到本地存储
        window.localStorage.setItem(
          "history",
          JSON.stringify(this.historyList)
        );
        this.$router.push({
          name: "result",
          query: {
            key: this.key,
          },
        });
      }
    },
    //输入框发生变化时调用
    oninput() {
      //防抖 放到定时器 触发则重新执行定时器
      clearTimeout(this.timerId);
      this.timerId = setTimeout(async () => {
        //setTimeout 不是setInterval
        if (this.key) {
          let res = await suggestAPI({
            q: this.key,
          });
          this.suggestList = res.data.data.options;
        }
      }, 200);
    },

    //清除历史记录
    ClearRecord() {
      window.localStorage.removeItem("history");
      this.historyList = [];
      this.clear = false;
    },
  },
  computed: {
    colocSuggestList() {
      // RegExp翻译为正则，ig为全局匹配并且不区分大小写
      let reg = new RegExp(this.key, "ig");
      return this.suggestList.map((v) => {
        return v.replaceAll(reg, `<span style="color:red;">${this.key}</span>`);
      });
    },
  },

  //历史记录，旧接口才用
  // async created() {
  //   let res = await getHistoryAPI();
  //   this.historyList = res.data.data.keywords;
  // },
};
</script>

<style lang="less" scoped>
.search {
  .clearlog {
    color: skyblue;
    font-size: 14px;
  }
}
</style>
